#include <WProgram.h>
#include <avr/io.h>
#include <avr/interrupt.h>
#include "ADC.h"


unsigned int adc_data[LAST_ADC_INPUT-FIRST_ADC_INPUT+1];

#define ADC_VREF_TYPE 0xC0

static unsigned char input_index=0;

// ADC interrupt service routine
// with auto input scanning
ISR (ADC_vect)
{

// Read the AD conversion result
adc_data[input_index]=ADCW;
// Select next ADC input
if (++input_index > (LAST_ADC_INPUT-FIRST_ADC_INPUT))
   input_index=0;
ADMUX=(ADC_VREF_TYPE & 0xff) | ((FIRST_ADC_INPUT+input_index) & 0x07);
if ((FIRST_ADC_INPUT+input_index) & 0x08) ADCSRB |= 0x10;
else ADCSRB &= 0xef;
// Delay needed for the stabilization of the ADC input voltage
delayMicroseconds(10);
// Start the AD conversion
ADCSRA|=0x40;
}


void adcInit()
{
  // ADC initialization
  // ADC Clock frequency: 250,000 kHz
  // ADC Voltage Reference: 2.56V, cap. on AREF
  // ADC Auto Trigger Source: None
  // Digital input buffers on ADC0: On, ADC1: On, ADC2: On, ADC3: On
  // ADC4: On, ADC5: On, ADC6: On, ADC7: On
  DIDR0=0x00;
  // Digital input buffers on ADC8: On, ADC9: On, ADC10: On, ADC11: On
  // ADC12: On, ADC13: On, ADC14: On, ADC15: On
  DIDR2=0x00;
  ADMUX=(FIRST_ADC_INPUT & 0x07) | (ADC_VREF_TYPE & 0xff);
  ADCSRA=0xCE;
  ADCSRB |=FIRST_ADC_INPUT & 0x08;
  
  // Global enable interrupts
  //#asm("sei")
}
